package ar.edu.itba.it.paw.domain;

import java.util.Date;

import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.ManyToOne;

import org.hibernate.annotations.OnDelete;
import org.hibernate.annotations.OnDeleteAction;

@Entity
public class Transaction extends PersistentAttributes {

	@ManyToOne
	private User buyer;
	@ManyToOne
	private User seller;
	private int quantity;
	private Date date;
	@ManyToOne(cascade = CascadeType.ALL)
	@OnDelete(action = OnDeleteAction.CASCADE)
	private Product product;
	
	
	protected Transaction(){

	}
	
	//This constructor is used to create transactions before they are inserted into the database
	public Transaction(User buyer, User seller, int quantity, Date date, Product product) {
		if(!(buyer == null || seller == null || product == null || quantity < 0 || date == null || product == null)){
			this.buyer = buyer;
			this.seller = seller;
			this.quantity = quantity;
			this.date = date;
			this.product = product;
		}else{
			throw new IllegalArgumentException("Invalid Arguments");
		}
	}

	public User getBuyer() {
		return buyer;
	}

	public User getSeller() {
		return seller;
	}

	public int getQuantity() {
		return quantity;
	}

	public Date getDate() {
		return date;
	}

	public Product getProduct() {
		return product;
	}	

	@Override
	public String toString() {
		return "Transaction [transactionId=" + getId() + ", buyerId="
				+ buyer + ", sellerId=" + seller + ", quantity=" + quantity
				+ ", date=" + date + "]";
	}

	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + ((buyer == null) ? 0 : buyer.hashCode());
		result = prime * result + ((date == null) ? 0 : date.hashCode());
		result = prime * result + ((product == null) ? 0 : product.hashCode());
		result = prime * result + quantity;
		result = prime * result + ((seller == null) ? 0 : seller.hashCode());
		return result;
	}

	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		Transaction other = (Transaction) obj;
		if (buyer == null) {
			if (other.buyer != null)
				return false;
		} else if (!buyer.equals(other.buyer))
			return false;
		if (date == null) {
			if (other.date != null)
				return false;
		} else if (!date.equals(other.date))
			return false;
		if (product == null) {
			if (other.product != null)
				return false;
		} else if (!product.equals(other.product))
			return false;
		if (quantity != other.quantity)
			return false;
		if (seller == null) {
			if (other.seller != null)
				return false;
		} else if (!seller.equals(other.seller))
			return false;
		return true;
	}

	public Double getSellingPrice() {
		return Double.valueOf(quantity * product.price);
	}
	
}
